package com.lagou.edu.mvcframework.security.impl;

import com.lagou.edu.mvcframework.annotations.LagouSecurity;
import com.lagou.edu.mvcframework.pojo.Handler;
import com.lagou.edu.mvcframework.security.SecurityService;

/**
 * @Description:
 * @Author: zhoushiduo
 * @Date: 2020/12/6 19:22
 */

public class SecurityServiceImpl implements SecurityService {

    /**
     * 为用户进行鉴权
     * @param handler 用户访问的资源
     * @param names 用户列表
     * @return true：允许；false：不允许
     */
    @Override
    public boolean isAllow(Handler handler, String[] names) {
        //鉴权
        Class<?> declaringClass = handler.getMethod().getDeclaringClass();
        boolean isAllow = true;

        //1.判断当前业务类是否有访问权限
        boolean annotationPresent = declaringClass.isAnnotationPresent(LagouSecurity.class);
        if (annotationPresent) {
            LagouSecurity annotation = declaringClass.getAnnotation(LagouSecurity.class);
            isAllow = doIsAllow(names, annotation);
        }

        //2.判断当前业务方法是否有访问权限
        boolean annotationPresentMethod = handler.getMethod().isAnnotationPresent(LagouSecurity.class);
        if (annotationPresentMethod) {
            LagouSecurity annotation = handler.getMethod().getAnnotation(LagouSecurity.class);
            //调用鉴权方法
            isAllow = doIsAllow(names, annotation);
        }
        return isAllow;
    }

    /**
     * 判读访问用户是否存在允许的用户范围内
     * @param names 用户列表
     * @param annotation 注解
     * @return true：存在；false：不存在
     */
    private boolean doIsAllow(String[] names, LagouSecurity annotation) {
        boolean isAllow = false;
        String[] value = annotation.value();
        for (String s : value) {
            if ("ALLUSER".equals(s)) {
                //默认是全部用户都放行
                isAllow = true;
                break;
            }
            if(null == names){
                //没有访问用户，不允许通过
                isAllow = false;
                break;
            }
            for (String name : names) {
                if (s.equalsIgnoreCase(name)) {
                    isAllow = true;
                    break;
                }
            }
            //拥有权限立即退出循环
            if (isAllow) {
                break;
            }
        }
        return isAllow;
    }
}
